<template>
  <div>
    <div>
      <el-dialog v-model="state.dialog" @open="dialogOpen" @close="dialogClose">
        <template #title v-if="props.disabled">
          <span>点击文件名称下载附件</span>
        </template>
        <el-upload
            v-bind="props"
            class="wgUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="handleBeforeUpload"
            :before-remove="handleBeforeRemove"
            :file-list="fileList"
            :on-success="onUploadSuccess"
            list-type="text"
            action="/api/system/annex/upload"
            :data="{ folderId: state.value }"
        >
          <el-button type="primary" icon="elementUpload" v-if="!props.disabled">上传</el-button>
          <template #tip v-if="!props.disabled">
            <div class="el-upload__tip">上传格式:{{ props.extensions }}</div>
            <div class="el-upload__tip">点击文件名称下载附件</div>
          </template>
        </el-upload>
      </el-dialog>
    </div>
    <div @click="state.dialog = true">
      <el-input
          v-if="props.mode == 'default'"
          v-model="state.text"
          readonly
          :placeholder="state.placeholder"
          class="input-with-select"
      >
        <template v-if="!props.disabled" #append>
          <el-button type="primary" icon="elementUpload"/>
        </template>
      </el-input>

      <el-button
          v-if="props.mode == 'button'"
          type="primary"
          icon="elementUpload"
      >上传
      </el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {ref, getCurrentInstance, reactive, watch} from "vue";
import type {UploadFile, UploadUserFile} from "element-plus";

import {downloadFile} from "/@/components/wigem/cloudFile"
import request from "/@/utils/request";

const {proxy}: any = getCurrentInstance();

const props = defineProps({
  extensions: {
    type: String,
    default:
        "gif,jpeg,jpg,png,psd,rar,zip,pdf,doc,docx,ppt,pptx,txt,xls,xlsx,jar",
  },
  mode: {
    type: String,
    default: "default",
  },
  modelValue: {
    type: String,
    default: "",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  text: {
    type: String,
    default: "",
  },
  isFarEnd: {
    type: Boolean,
    default: true,
  },
  open: {
    type: Boolean,
    default: false,
  },
});
//声名文件列表
let fileList = ref<UploadUserFile[]>([]);
const state = reactive({
  dialog: false,
  value: "",
  text: "",
  fileList: {},
  placeholder: "点我进行附件上传",
});

const init = () => {
  state.value = props.modelValue;
  state.text = props.text;
  if (proxy.$wigem.isEmpty(state.value)) {
    state.value = proxy.$wigem.uuidString("N");
  }
  /*console.log(props.open)
  if (props.open) {
      state.dialog = true
  }*/
  handleInputTextReload();
};

/**
 * @name 删除附件
 */
const handleRemove = (file: UploadFile, fileList: UploadFile[]) => {
  if (props.disabled) {
    proxy.$wigem.alert.warning("只读模式禁止删除附件");
    return false;
  }
  onRemoveAnnex(file).then((res) => {
    getFiles();
  });
};

/**
 * @name 删除附件
 */
const onRemoveAnnex = (file: UploadFile) => {
  return request({
    url: "/api/system/annex/delete/" + file.annexId,
    method: "delete",
  });
};

/**
 * @name   预览附件
 */
const handlePreview = (file: UploadFile) => {
  let url = "";

  if (!props.isFarEnd) {
    url = "/api/system/annex/downFile?fileId=";
  }

  let fileFormat = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
  let downLoadParams = {
    annexId: file.annexId,
    fileFormat: fileFormat,
    fileName: file.name,
    url: url
  }
  //下载
  downloadFile(downLoadParams);
};

/**
 * @name   上传附件前执行格式验证
 */
const handleBeforeUpload = (file: UploadFile) => {
  let extentionType = file.name
      .substring(file.name.lastIndexOf("."))
      .toLowerCase();
  if (props.extensions.indexOf(extentionType.replace(".", "")) == -1) {
    proxy.$wigem.alert.warning(
        "禁止上传此格式文件，参考格式:" + props.extensions
    );
    return false;
  }
};

/**
 * @name 获取已上传附件
 */
const getFiles = () => {
  request({
    url: "/api/system/annex/query/files/" + state.value,
    method: "get",
  }).then((res) => {
    if (res.success) {
      fileList.value.splice(0, fileList.value.length);
      for (let index = 0; index < res.data.length; index++) {
        let fileObj = {
          name: res.data[index].fileName,
          url: "",
          annexId: res.data[index].annexId,
        };
        fileList.value.push(fileObj);
      }
    }
  });
};

const handleInputTextReload = () => {
  request({
    url: "/api/system/annex/query/filesName/" + state.value,
    method: "get",
    params: {},
  }).then((res) => {
    if (res.code == 200) {
      state.text = res.data;
      if (state.text == "") {
        state.text = props.text;
        if (props.disabled) {
          state.placeholder = "暂无附件";
        }
      }
    }
  });
};
const handleBeforeRemove = () => {
};

const openUploadForm = () => {
  state.dialog = true;
};
const dialogClose = () => {
  handleInputTextReload();
  // fileList = ref<UploadUserFile[]>([]);
};
const dialogOpen = () => {
  getFiles();
};

//上传文件成功
const onUploadSuccess = (res, file) => {
  proxy.$emit("onUploadSuccess", res.data);
  getFiles();
};
init();
watch(
    () => props.modelValue,
    () => {
      init();
      getFiles();
      setTimeout(() => {
        dialogClose();
      }, 100);
    }
);
</script>
